
/*
 * @Author: silas 
 * @Date: 2021-05-17 15:11:55 
 * @Last Modified by: silas
 * @Last Modified time: 2021-05-21 18:39:24
 */
<template>
  <div class="tobBtoC">
    <div class="contentTopTitle">
      <div class="title">收入预估参考资料</div>
    </div>
    <div>
      <el-form :inline="true" :model="form" label-width="80px" class="formList">
        <el-form-item label="选择区域" style="width: 18%">
          <dx-cascader :area_id.sync="form.areaId" />
        </el-form-item>
        <el-form-item label="账期" style="width: 18%">
          <el-date-picker v-model="form.time" type="month" placeholder="选择账期" value-format="yyyyMM"></el-date-picker>
        </el-form-item>
        <el-form-item label="统计日期" style="width: 15%">
          <el-select v-model="form.version">
            <el-option v-for="(it, i) in version" :key="i" :label="it.label" :value="it.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="存增量" style="width: 17%">
          <el-select v-model="form.clType">
            <el-option v-for="(it, i) in clType" :key="i" :label="it.label" :value="it.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="width: 28%">
          <el-button style="margin-left: 10px" size="mini" type="primary" @click="handle_search">查询</el-button>
          <!-- <el-button @click="handle_down()" size="mini"
						>模板下载</el-button
					>
					<el-button
                    type="orange"
                    @click="
                        dialogVisible = true;
                        importForm.year = '';
                        importForm.typeId = '';
                        importForm.version = '';
                        fileList = [];
                    "
                    size="mini"
                    >导入</el-button
                >
                -->
          <el-button size="mini" type="orange" @click="handle_export">导出</el-button>
          <el-button size="mini" type="orange" @click="handlExportTwo">二级导出</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-content clearfix">
      <!-- <p class="g-unit">单位: 万元</p> -->
      <div class="content">
        <div class="tableBox">
          <el-table id="table" v-loading="tableLoading" :data="tableData" style="width: 100%" class="tableTh28" border stripe ref="table">
            <el-table-column min-width="140" label="收入来源大类" prop="incomeCatgName" />
            <el-table-column min-width="170" label="收入来源子类" prop="ysIncomeName" />
            <el-table-column min-width="100" label="收入来源编码" prop="incomeCode" />
            <el-table-column min-width="100" show-overflow-tooltip label="收入来源名称" prop="incomeName" />
            <el-table-column v-for="(it, i) in titles" :key="i" :label="it.label">
              <el-table-column v-for="(item, index) in it.titles" :key="index" :label="item.label" :prop="item.horizonIndexId" min-width="90">
                <el-table-column min-width="90" v-for="(data, dIndex) in item.origin" :key="'third' + dIndex" :prop="data.horizonIndexId" :label="data.horizonIndexName"></el-table-column>
              </el-table-column>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <el-dialog title="导入文件" append-to-body :visible.sync="dialogVisible" width="450px">
      <el-form :model="importForm" ref="importForm" :rules="rules">
        <el-form-item label="账期" prop="year" label-width="80px">
          <el-date-picker v-model="importForm.year" type="month" size="mini" placeholder="选择时间" value-format="yyyyMM"></el-date-picker>
        </el-form-item>
        <el-form-item label-width="80px" label="版本" prop="version">
          <el-select v-model="importForm.version" size="mini" clearable style="width: 220px">
            <el-option v-for="(it, i) in importVersion" :key="i" :label="it.label" :value="it.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label-width="80px" label="类别" prop="typeId">
          <el-select v-model="importForm.typeId" size="mini" clearable style="width: 220px">
            <el-option v-for="(it, i) in typeslist" :key="i" :label="it.typeName" :value="it.typeId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传文件" prop="file">
          <el-upload size="mini" :limit="1" accept=".xls, .xlsx" class="avatar-uploader" :auto-upload="false" :file-list="fileList" :on-change="changeFile" action>
            <el-button size="mini" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>

      <div slot="footer">
        <div class="dialog-footer">
          <el-button size="mini" type="primary" @click="handle_import()">确定</el-button>
          <el-button size="mini" @click="dialogVisible = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import prefixAPI from "@/api/prefixAPI";
import { getCookie } from "@/common/js/cookie";
import { getSessionStorage } from "@/common/js/storage";
import { $budgetAPI } from "@/api";
import FileSaver from "file-saver";
import XLSX from "xlsx";
import costRevenueVue from "../showPdf/costRevenue.vue";
export default {
  name: "lightEva",
  data() {
    return {
      form: {
        areaId: "",
        time: "",
        version: "24",
        clType: '0'
      },
      tableData: [],
      tableLoading: false,
      version: [
        { label: "24日", value: "24" },
        { label: "28日", value: "28" },
      ],
      clType: [
        { label: "全量客户", value: "0" },
        { label: "存量客户", value: "1" },
      ],
      importForm: {
        year: "",
        version: "",
        typeId: "",
      },
      importVersion: [
        { label: "24日", value: "24" },
        { label: "28日", value: "28" },
      ],
      dialogVisible: false,
      fileList: [],
      rules: {
        year: [
          { required: true, message: "请选择时间", trigger: "blur" },
        ],
        version: [
          { required: true, message: "请选择版本", trigger: "blur" },
        ],
        typeId: [
          { required: true, message: "请选择类别", trigger: "blur" },
        ],
      },
      typeslist: [],
      titles: [],
      isExport: false,
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    async init() {
      let that = this;

      that.accountInfo = JSON.parse(getSessionStorage("accountInfo"));
      that.form.areaId = that.accountInfo.areaId;

      that.form.time = new Date().getDate() > 22 ?
        that.moment().subtract(0, "months").format("YYYYMM") :
        that.moment().subtract(1, "months").format("YYYYMM");

      // that.getTypes()
      that.getData();
    },
    getData() {
      var that = this,title;
      that.tableLoading = true;
      $budgetAPI.getYuGuData(
        {
          areaId: that.form.areaId,
          acctMonth: that.form.time,
          fcDate: that.form.version,
          clType: that.form.clType
        },
        (res) => {
          that.tableData = [];
          if (res && res.code == 0) {
            res.content.data.map((it) => {
              it.detailList.map((item) => {
                it[item.indexId] = item.indexValue;
              });
            });
            title = that.mergeTitles(res.content.titles, "class3");
            title.map(it => {
              it.titles = that.mergeTitles(it.origin, "class1");
            })
            title.map((it) => {
              it.titles.map(item => {
                if (item.origin.length == 1) {
                  item.origin = [];
                }
              })

            });
            that.titles = title;
            that.tableData = res.content.data;
          }
          that.tableLoading = false;
        }
      );
    },
    handle_search() {
      // if(!this.form.time || !this.form.fcDate) {
      // 	this.$message.error("请选择账期和版本");
      // 	return false
      // }
      this.getData();
    },
    handle_time(val) {
      this.form.time = val;
      this.form.fcDate = "";
      this.getFC(val);
    },
    handle_export() {
      var xlsxParam = {
        raw: true,
      }; //转换成excel时，使用原始的格式，这样导出的时候数字过长不会变成科学计数法

      if (!this.tableData.length) {
        this.$message.error("暂无数据可导出");
        return false;
      }
      let workbook = XLSX.utils.book_new();
      let ws1 = XLSX.utils.table_to_sheet(
        document.querySelector("#table"),
        xlsxParam
      );
      XLSX.utils.book_append_sheet(workbook, ws1, "收入预估参考资料");
      let wbout = XLSX.write(workbook, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });

      this.loading = this.$loading({
        lock: true,
        text: "正在",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], {
            type: 'application/octet-stream;charset=utf-8"',
          }),
          "收入预估参考资料.xlsx"
        );
        this.loading.close();
        this.isExport = false;
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbOut);
      }
    },
    handle_del(row) {
      var that = this;

      that.$confirm("是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        $budgetAPI.getDeleteRecord(
          {
            recordId: row.recordId,
            token: getCookie("token"),
          },
          (res) => {
            if (res.code == 0) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            } else {
              this.$message({
                type: "error",
                message: res.message,
              });
            }
            that.getData();
          }
        );
      });
    },
    handlExportTwo(){
        let token = getCookie("token");
      let areaId = this.form.areaId;
      let acctMonth = this.form.time;
      let fcDate = this.form.version;
      let clType = this.form.clType;
    console.log(areaId);
      if (process.env.NODE_ENV == "development") {
          console.log('-------1111111----------');
        window.location.href = prefixAPI.loc +
          "/api/yuGuWebDataR3/exportData?token=" +token +
          "&areaId=" +areaId +
          "&acctMonth=" +acctMonth +
          "&fcDate=" +fcDate+
          "&clType=" +clType;
      } else if (process.env.NODE_ENV == "production") {
        window.location.href = prefixAPI.hp +
          "/api/yuGuWebDataR3/exportData?token=" +token +
          "&areaId=" +areaId +
          "&acctMonth=" +acctMonth +
          "&fcDate=" +fcDate+
          "&clType=" +clType;
      }

    },
    handle_down() {
      var token = getCookie("token");

      window.location.href =
        prefixAPI.hp +
        "/api/incomeEstimateImport/downTemplate?&token=" +
        token;
    },
    // 批量导入上传文件传递数据
    changeFile(file, fileList) {
      this.fileList = fileList;
      this.param = new FormData();
      this.param.append("file", file.raw);
    },
    // 导入
    handle_import(type) {
      var that = this;

      that.$refs["importForm"].validate((valid) => {
        if (valid) {
          if (that.fileList.length == 0) {
            that.$message({
              message: "请选择需要上传的文件",
              type: "warning",
            });
            return false;
          }
          that.param.append("version", that.importForm.version);
          that.param.append("token", getCookie("token"));
          that.param.append("acctMonth", that.importForm.year);
          that.param.append("typeId", that.importForm.typeId);
          $budgetAPI.importIncomeEstimateData(
            that.param,
            (res) => {
              if (res.code == 0) {
                that.$message({
                  message: "导入成功",
                  type: "success",
                });
                that.getData();
              } else {
                that.$message.error(res.message);
              }
              that.dialogVisible = false;
            },
            (err) => {
              that.dialogVisible = false;
            }
          );
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    mergeTitles(data, type) {
      let tempArr = [];
      let afterData = [];
      for (let i = 0; i < data.length; i++) {
        if (tempArr.indexOf(data[i][type]) === -1) {
          afterData.push({
            label: data[i][type],
            horizonIndexId: data[i].horizonIndexId,
            origin: [data[i]],
          });
          tempArr.push(data[i][type]);
        } else {
          for (let j = 0; j < afterData.length; j++) {
            if (afterData[j].label == data[i][type]) {
              afterData[j].origin.push(data[i]);
              break;
            }
          }
        }
      }
      return afterData;
    },

    // hanlde_version(val) {
    // 	this.form.fcDate = val;
    // 	this.getData();
    // }
  },
};
</script>

<style lang="scss" scoped>
.remark {
  padding-top: 5px;
  text-align: left;
  .attention {
    font-weight: bold;
  }
}
.table-content {
  .table-header {
    display: flex;
    justify-content: space-between;
    .table-title {
      font-size: 14px;
      font-weight: bold;
      height: 30px;
      line-height: 30px;
      span {
        display: inline-block;
        width: 5px;
        height: 5px;
        background-color: #418ee9;
        border-radius: 1000%;
        overflow: hidden;
        margin-right: 10px;
        margin-bottom: 3px;
      }
    }
  }
  .content {
    margin-top: 15px;
  }
}
</style>
